<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部标题 -->
    <div class="py-4 text-center bg-[#07C160]">
      <h1 class="text-2xl font-bold text-white">乐刷微信支付</h1>
    </div>

    <div class="max-w-md mx-auto p-4">
      <!-- 收银台 -->
      <a-card class="mb-4 shadow-sm" :bordered="false">
        <!-- 金额输入区域 -->
        <div class="mb-6">
          <div class="text-gray-500 mb-2">请输入支付金额</div>
          <div class="flex items-center">
            <span class="text-2xl font-bold mr-2">¥</span>
            <a-input-number
              v-model:value="amount"
              :precision="2"
              :min="0.01"
              :max="50000"
              class="text-2xl font-bold flex-1"
              :class="[
                'custom-input',
                amount && amount > 0 ? 'text-gray-800' : 'text-gray-400'
              ]"
              placeholder="请输入金额"
              style="width: 100%;"
            />
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="mb-6">
          <div class="text-gray-500 mb-2">备注信息（选填）</div>
          <a-input
            v-model:value="description"
            placeholder="请输入备注信息"
            class="custom-input"
          />
        </div>

        <!-- 付款按钮 -->
        <a-button
          block
          size="large"
          :disabled="!amount || amount <= 0 || !openId"
          class="custom-button"
          @click="goToPay"
        >
          立即支付
        </a-button>

        <!-- 显示OpenID -->
        <div v-if="openId" class="mt-4 text-center text-sm text-gray-500">
          OpenID: {{ openId }}
        </div>

        <!-- 显示支付信息 -->
        <div v-if="openId" class="mt-4">
          <a-descriptions title="支付信息" bordered>
            <a-descriptions-item label="订单号">
              {{ orderNo }}
            </a-descriptions-item>
            <a-descriptions-item label="支付金额">
              ¥{{ amount }}
            </a-descriptions-item>
            <a-descriptions-item label="支付渠道">
              乐刷微信支付
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import { useRoute } from 'vue-router'

const route = useRoute()
const orderNo = ref(route.query.orderNo as string)
const timestamp = ref(route.query.timestamp as string)
const nonce = ref(route.query.nonce as string)
const sign = ref(route.query.sign as string)
const openId = ref('')

// 检测用户代理
const userAgent = navigator.userAgent
const isWechat = computed(() => /MicroMessenger/i.test(userAgent))

// 支付信息
const amount = ref<number>(0.01)
const description = ref('')
const payParams = ref<any>(null)

// 声明微信JSBridge类型
declare global {
  interface Window {
    WeixinJSBridge?: {
      invoke: (api: string, config: any, callback: (res: { err_msg: string }) => void) => void;
    };
  }
}

// 验证签名
const verifySign = async () => {
  try {
    console.log('开始验证签名，参数:', {
      orderNo: orderNo.value,
      timestamp: timestamp.value,
      nonce: nonce.value,
      sign: sign.value
    })

    const response = await axios.post('/api/merchant/verify-sign', {
      orderNo: orderNo.value,
      timestamp: timestamp.value,
      nonce: nonce.value,
      sign: sign.value
    })

    console.log('签名验证响应:', response.data)
    return response.data.code === 0
  } catch (error) {
    console.error('验证商户请求签名失败:', error)
    return false
  }
}

// 验证URL参数
const validateUrlParams = async () => {
  // 1. 检查必要参数是否存在
  // if (!orderNo.value || !nonce.value || !sign.value) {
  //   message.error('缺少必要参数')
  //   return false
  // }

  // 2. 验证签名
  const isValidSign = await verifySign()
  if (!isValidSign) {
    message.error('验证商户请求签名失败')
    return false
  }

  return true
}

// 获取微信OpenID
const getWechatOpenId = async () => {
  if (!isWechat.value) return

  try {
    // 1. 检查URL中是否已有code
    const code = route.query.code as string
    if (code) {
      // 2. 使用code获取openid
      const response = await axios.post('/api/auth/wechat/user', { code })
      if (response.data.code === 0) {
        openId.value = response.data.data.openId
        message.success('获取OpenID成功')
      } else {
        message.error(response.data.message || '获取OpenID失败')
      }
    } else {
      // 3. 如果没有code，自动生成授权链接并跳转
      const redirectUri = encodeURIComponent(window.location.href)
      const response = await axios.get(`/api/auth/wechat/url?redirectUri=${redirectUri}`)
      if (response.data.authUrl) {
        window.location.href = response.data.authUrl
      }
    }
  } catch (error) {
    console.error('获取OpenID失败:', error)
    message.error('获取OpenID失败')
  }
}

// 跳转到支付页面
const goToPay = async () => {
  try {
    // 1. 输入金额验证
    if (!amount.value || amount.value <= 0) {
      message.error('请输入有效金额')
      return
    }

    if (!openId.value) {
      message.error('请先获取OpenID')
      return
    }

    // 2. 调用支付接口
    console.log('开始创建支付订单')
    const requestData = {
      orderNo: orderNo.value,
      amount: amount.value,
      description: description.value || '商品购买',
      channel: 'leshua_wxpay',
      openId: openId.value
    }
    console.log('支付订单请求参数:', requestData)

    const response = await axios.post('/api/leshua/wxpay/v1/payments', requestData)
    console.log('支付订单响应:', response.data)

    if (response.data.code === 0) {
      // 3. 调用微信支付JSAPI
      const payParams = response.data.data.payParams
      console.log('微信支付参数:', payParams)

      if (typeof window.WeixinJSBridge !== 'undefined') {
        window.WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          payParams,
          function(res: { err_msg: string }) {
            // 4. 处理支付结果
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              console.log('支付成功')
              message.success('支付成功')
              // 直接返回微信首页
              window.WeixinJSBridge.invoke('closeWindow', {}, function() {
                // 回调函数可以为空
              })
            } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              console.log('用户取消支付')
              message.info('支付已取消')
            } else {
              console.error('支付失败:', res.err_msg)
              message.error('支付失败')
              // 跳转到支付失败页面
              window.location.href = `/pay/leshua-wxpay/fail?orderNo=${orderNo.value}&error=${res.err_msg}`
            }
          }
        )
      } else {
        console.error('非微信环境')
        message.error('请在微信环境中支付')
      }
    } else {
      console.error('创建支付订单失败:', response.data)
      message.error(response.data.message || '创建支付订单失败')
    }
  } catch (error: any) {
    console.error('支付过程发生错误:', error)
    // 显示详细的错误信息
    if (error.response) {
      console.error('错误响应:', error.response.data)
      message.error(`创建支付订单失败: ${error.response.data.message || error.message}`)
    } else if (error.request) {
      console.error('请求错误:', error.request)
      message.error('网络请求失败，请检查网络连接')
    } else {
      message.error(`创建支付订单失败: ${error.message}`)
    }
  }
}

// 页面加载时验证参数
onMounted(async () => {
  // 1. 验证URL参数
  const isValid = await validateUrlParams()
  if (!isValid) {
    // 如果验证失败，可以考虑跳转到错误页面
    return
  }

  // 2. 在微信环境中自动获取OpenID
  if (isWechat.value) {
    getWechatOpenId()
  }
})
</script>

<style scoped>
.ant-card {
  border-radius: 8px;
}

.custom-input {
  border-color: #e5e7eb;
  border-radius: 8px;
  transition: all 0.3s;
}

.custom-input:hover,
.custom-input:focus {
  border-color: #07C160;
  box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.1);
}

.custom-button {
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #07C160;
  border-color: #07C160;
  color: white;
  transition: all 0.3s;
}

.custom-button:hover {
  background-color: #06ae56;
  border-color: #06ae56;
  color: white;
}

.custom-button:active {
  background-color: #059a4d;
  border-color: #059a4d;
  color: white;
}

.custom-button[disabled] {
  background-color: #e5e7eb;
  border-color: #e5e7eb;
  color: #9ca3af;
}

.ant-descriptions-item-label {
  width: 120px;
  color: #666;
}

.ant-descriptions-item-content {
  color: #333;
}

.ant-input-number {
  width: 100%;
}

.ant-input-number-input {
  height: 44px;
  font-size: 20px;
}

.ant-input {
  height: 36px;
  border-radius: 8px;
}
</style>